﻿using Flurl.Http;
using System.Threading.Tasks;

namespace Pay.Core.WeiXin {
	public class OAuthApi {
		/// <summary>
		/// 获取验证地址
		/// </summary>
		/// <param name="appId"></param>
		/// <param name="redirectUrl"></param>
		/// <param name="scope">snsapi_base:只能获取openid,snsapi_userinfo:可以获取用户信息</param>
		/// <returns></returns>
		public static string GetAuthorizeUrl(string appId, string redirectUrl, string scope = "snsapi_base") {
#if (DEBUG)
			//var log = IocHelper.Get<ILogHelper>("ui_error");
			//log.Info(appId);
			//log.Info(redirectUrl);
#endif
			var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect",
					appId, WebHelper.UrlEncode(redirectUrl), scope);
#if (DEBUG)
			//log.Info(url);
#endif
			return url;
		}

		/// <summary>
		/// 获取token
		/// </summary>
		/// <param name="appId"></param>
		/// <param name="appSecret"></param>
		/// <param name="code"></param>
		/// <returns></returns>
		public static async Task<weixin_token> GetAccessToken(string appId, string appSecret, string code) {
			string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
				appId, appSecret, code);
			var weixinToken = await url.GetAsync().ReceiveJson<weixin_token>();
			return weixinToken;
		}

		/// <summary>
		/// 获取收货地址需要的JS参数
		/// </summary>
		/// <param name="appId"></param>
		/// <param name="accessToken"></param>
		/// <param name="url"></param>
		/// <returns></returns>
		public static wexin_address_js_query GetAddressQuery(string appId, string accessToken, string url) {
			string timeStamp = TenPayV3Util.GetTimestamp();
			string nonceStr = TenPayV3Util.GetNoncestr();

			RequestHandler paySignReqHandler = new RequestHandler(null);
			paySignReqHandler.SetParameter("accesstoken", accessToken);
			paySignReqHandler.SetParameter("appid", appId);
			paySignReqHandler.SetParameter("noncestr", nonceStr);
			paySignReqHandler.SetParameter("timestamp", timeStamp);
			paySignReqHandler.SetParameter("url", url);
			var addrSign = paySignReqHandler.CreateSHA1Sign();
			wexin_address_js_query js_query = new wexin_address_js_query();
			js_query.app_id = appId;
			js_query.addrSign = addrSign;
			js_query.nonceStr = nonceStr;
			js_query.timeStamp = timeStamp;

			return js_query;
		}

		/// <summary>
		/// 获取凭证接口
		/// </summary>
		/// <param name="grant_type">获取access_token填写client_credential</param>
		/// <param name="appId">第三方用户唯一凭证</param>
		/// <param name="appSecret">第三方用户唯一凭证密钥，既appsecret</param>
		/// <returns></returns>
		public static async Task<weixin_token> GetToken(string appId, string appSecret, string grant_type = "client_credential") {
			var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appId, appSecret);
			var weixinToken = await url.GetAsync().ReceiveJson<weixin_token>();
			return weixinToken;
		}

		/// <summary>
		/// 获取token和user_info
		/// </summary>
		/// <param name="appId"></param>
		/// <param name="appSecret"></param>
		/// <param name="code"></param>
		/// <returns></returns>
		public static async Task<weixin_user_info> GetUserInfo(string appId, string appSecret, string code) {
			string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
				appId, appSecret, code);
			var weixinToken = await url.GetAsync().ReceiveJson<weixin_token>();
			url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", weixinToken.access_token, weixinToken.openid);
			var weixin_user = await url.GetAsync().ReceiveJson<weixin_user_info>();
			if (!string.IsNullOrEmpty(weixin_user.headimgurl)) {
				try {
					weixin_user.file_byte = await (weixin_user.headimgurl + "/132").GetBytesAsync();
				} catch {
				}
			}
			return weixin_user;
		}
	}
}
